﻿using System;
using System.Linq;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Http;
using ELearning.Common.Model;
using ELearning.Common.Oprator;
using ELearning.Models;
using ELearning.Models.ViewModel.YTJYAdmin.Account;

namespace ELearning.API.Controllers.YTJYAdminController
{
    /// <summary>
    /// 账号相关
    /// </summary>
    public class LoginController : BaseApiController
    {
        /// <summary>
        /// 用户操作service
        /// </summary>
        protected ESysUserService userService = new ESysUserService();

        /// <summary>
        /// 登录token记录操作service
        /// </summary>
        private TLoginTokenService tlLoginTokenService => new TLoginTokenService();

        /// <summary>
        /// 运营平台登录接口
        /// </summary>
        [HttpPost, Route("api/ELogin/AdminLogin")]
        [AllowAnonymous]
        public ServiceResponse<AdminLoginViewModel> AdminLogin(AdminLoginRequest request)
        {
            var viewModel = new AdminLoginViewModel();
            //var p = DESProvider.EncryptString(request.Password).Trim();
            var p = request.Password.Trim();
            var users = userService.FindList(u => !u.IsDelete && u.LoginName == request.LoginName.Trim());
            if (users.Any())
            {
                var user = users.FirstOrDefault(u => !u.IsDelete && u.LoginName == request.LoginName.Trim() && u.Password == p);

                if (user.IsNotNull())
                {
                    viewModel.Token = GuidUtil.NewSequentialId().ToString();
                    var currentUserModel = new OperatorModel
                    {
                        Email = user.Email,
                        HeadPhoto = user.HeadPhoto,
                        LoginName = user.LoginName,
                        OrgCode = user.OrgCode,
                        //OrgName = orgService.Find(w => w.org_code == user.OrgCode)?.org_name ?? string.Empty,
                        MobilePhone = user.MobilePhone,
                        Position = user.Position,
                        Remark = user.Remark,
                        UserId = user.UserID,
                        UserIp = IpHelp.GetClientIp(),
                        UserName = user.UserName,
                        UserType = user.UserType,
                    };

                    //保存登录token日志
                    tlLoginTokenService.Add(new TLoginToken
                    {
                        Id = Guid.NewGuid(),
                        CreateTime = DateTime.Now,
                        CreateUserId = user.UserID,
                        IsDelete = false,
                        PassDateTime = DateTime.Now.AddHours(8),
                        Token = viewModel.Token,
                        UpdateTime = DateTime.Now,
                        UpdateUserId = user.UserID,
                        UserId = user.UserID,
                        Source = 2
                    });
                    OperatorProvider.Provider.AddCurrent(viewModel.Token, currentUserModel);
                }
                else
                {
                    return ServiceResponse<AdminLoginViewModel>.WarningResponse(CommonConst.PASSWORD_ERROR, viewModel);
                }
            }
            else
            {
                return ServiceResponse<AdminLoginViewModel>.WarningResponse(CommonConst.USER_ERR_LOGIN, viewModel);
            }

            return ServiceResponse<AdminLoginViewModel>.SuccessResponse(viewModel);
        }

        /// <summary>
        /// 发版后使用，把用户登录的信息放到内存中，临时使用，使用。redis 后废弃
        /// </summary>
        [HttpPost, Route("api/ELogin/ResetCache")]
        [AllowAnonymous]
        public object ResetCache()
        {
            var tokens = tlLoginTokenService.FindList(l => !l.IsDelete && l.PassDateTime > DateTime.Now).ToList();
            var userIds = tokens.Select(l => l.UserId).ToList();
            var users = userService.FindList(u => !u.IsDelete && userIds.Contains(u.UserID)).ToList();

            foreach (var user in users)
            {
                var currentUserModel = new OperatorModel
                {
                    Email = user.Email,
                    HeadPhoto = user.HeadPhoto,
                    LoginName = user.LoginName,
                    OrgCode = user.OrgCode,
                    //OrgName = orgService.Find(w => w.org_code == user.OrgCode)?.org_name ?? string.Empty,
                    MobilePhone = user.MobilePhone,
                    Position = user.Position,
                    Remark = user.Remark,
                    UserId = user.UserID,
                    UserIp = IpHelp.GetClientIp(),
                    UserName = user.UserName,
                    UserType = user.UserType,
                };
                var token = tokens.Where(l => l.UserId == user.UserID).OrderByDescending(l => l.PassDateTime).FirstOrDefault();

                if (token.IsNotNull())
                {
                    OperatorProvider.Provider.AddCurrent(token.Token, currentUserModel, token.PassDateTime);
                }

            }
            return true;
        }
    }
}